#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：socket不同通路收发信息.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2024/12/29 13:15 
"""

import socket
from queue import Queue
import threading


class DualCommunication:
	def __init__(self, host, port_send, port_receive):
		self.host = host
		self.port_send = port_send
		self.port_receive = port_receive
		self.message_queue = Queue()

	def start_sender(self):
		threading.Thread(target=self._send, args=()).start()

	def start_receiver(self):
		threading.Thread(target=self._receive, args=()).start()

	def _send(self):
		with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
			s.connect((self.host, self.port_send))
			while True:
				message = self.message_queue.get()
				s.sendall(message.encode())
				print(f"发送：{message}")

	def _receive(self):
		with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
			s.bind((self.host, self.port_receive))
			s.listen()
			conn, addr = s.accept()
			with conn:
				print(f"连接地址：{addr}")
				while True:
					data = conn.recv(1024)
					if not data:
						break
					print(f"接收确认：{data.decode()}")


# 使用
if __name__ == "__main__":
	dual_comm = DualCommunication('localhost', 12346, 12347)
	dual_comm.start_sender()
	dual_comm.start_receiver()
	dual_comm.message_queue.put("Hello, Server!")
